package com.neuedu.his.common.core;

import com.alibaba.fastjson.JSON;
import com.neuedu.his.common.BusinessException;
import com.neuedu.his.common.Page;
import com.neuedu.his.common.Ret;
import com.neuedu.his.controller.DeptController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseController<E> extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri = req.getRequestURI();
        //获取方法名
        String method = "";
        if(uri.contains("/") && uri.lastIndexOf("/")+1 < uri.length()){
            method = uri.substring(uri.lastIndexOf("/")+1);
        }

        //如果不满足上述 条件   type: test    test()
        //反射 根据前面的方法名来调用当前类的方法
        Method declaredMethod = null;
        Object ret;
        try {
            if(method == null || "".equals(method)){
                throw new BusinessException("请求路径有误，请检查 uri:"+uri);
            }
            //getDeclaredMethod 获取本类  DeptController.list
            // getMethod       本类 和父类  public
            declaredMethod = this.getClass().getMethod(method, HttpServletRequest.class, HttpServletResponse.class);
            declaredMethod.setAccessible(true); //private  也可以调用  会破坏 java的封装 到机制

            //返回结果
            if(declaredMethod.getReturnType().equals(Void.TYPE)){
                declaredMethod.invoke(this,req,resp);
            }else{
                ret = declaredMethod.invoke(this,req,resp);
                writeJSON(resp,Ret.success(ret));
            }

        } catch (NoSuchMethodException ne){
            ret = Ret.fail("请求路径有误，请检查 uri:"+uri);
            writeJSON(resp,ret);
            ne.printStackTrace();
        } catch(Exception e) {
            ret = Ret.fail(e.getMessage());
            writeJSON(resp,ret);
            throw new RuntimeException(e);

        }




    }


    protected void writeJSON(HttpServletResponse resp, Object obj) throws IOException {
        String json = JSON.toJSONString(obj);
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter writer = resp.getWriter();
        writer.write(json);
        writer.flush();
        writer.close();
    }

    protected void writeString(HttpServletResponse resp, String str) throws IOException {

        resp.setContentType("application/json;charset=utf-8");

        PrintWriter writer = resp.getWriter();
        writer.write(str);
        writer.flush();
        writer.close();
    }

    public abstract BaseService getService();



    public Page list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Page page = getService().queryList(req);
        return page;
    }


    /**
     *  根据主键查询记录
     * @param req
     * @param resp
     * @throws IOException
     */
    public <E> E queryById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        E entity = (E) getService().queryById(req);
        return entity;
    }


    public Map deleteById(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        boolean success = getService().deleteById(req);

        Map result  = new HashMap();
        result.put("success",success);

        return result;
    }


    public Map save(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        boolean success = getService().save(req);

        Map result  = new HashMap();
        result.put("success",success);

        return result;
    }
    public Map update(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        boolean success = getService().update(req);
        Map result  = new HashMap();
        result.put("success",success);
        return result;
    }

}
